package com.tom.config.interceptor;

import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.tom.config.properties.SystemServiceProperty;

@Component
public class LoginTimeInterceptor extends HandlerInterceptorAdapter {
	@Autowired
	private SystemServiceProperty serviceProperty;

	// 在控制器执行前调用
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println(serviceProperty.getStarthour() + ">>>>>>>>>>>>>>>>>>>" + serviceProperty.getEndhour());
		System.out.println("执行preHandle方法-->01");
		Calendar cal = Calendar.getInstance();
		// 获得当前时间对应的小时数,例如：12:05-->12,13:15-->13
		int hour = cal.get(Calendar.HOUR_OF_DAY);
		if (serviceProperty.getStarthour() <= hour && hour < serviceProperty.getEndhour()) {
			return true; // 通过拦截器，继续执行请求
		} else {// 给定的时间之外禁止登录
			request.setAttribute("msg", "非登录时段");
			// TODO 可以在拦截器中跳转吗
			request.getRequestDispatcher("/standby").forward(request, response);
			return false; // 没有通过拦截器，返回登录页面
		}
	}

	// 在后端控制器执行后调用
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("执行postHandle方法-->02");
		super.postHandle(request, response, handler, modelAndView);
	}

	// 整个请求执行完成后调用
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("执行afterCompletion方法-->03");
		super.afterCompletion(request, response, handler, ex);
	}
}
